import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { observer, inject } from 'mobx-react';
import {toJS} from 'mobx';
import { withRouter,Route } from 'react-router-dom';
import { Tools, SegmentedControl, Flex, Icon, List, Popover, DatePicker, Modal, Select, TextareaItem,NoticeBar, Bubble } from 'weaver-mobile';
import { RouteLayout, Reply, Form, CKRichText,Browser, BrowserHrm } from 'weaver-mobile-page';
import QueueAnim from 'rc-queue-anim';
import { TitleUtil, shadowEqual, searchToQuery } from '../../util/';
import SendEnd from './SendEnd';
import MailInput from '../widget/MailInput';
import Api from '../../apis/setting';

const getLabel = Tools.getLabel;
const NoMask = Reply.NoMask;
const CKRichEditor = CKRichText.CKRichEditor;
const ButtonGroup = RouteLayout.ButtonGroup;

@inject('newStore','listStore')
@withRouter
@observer
export default class New extends Component {
  static defaultProps = {
    prefixCls: 'email-new',
  }

  constructor(props) {
    super(props);
    this.state = {
      isSpaceFull: false
    };
    this.autoSaveDraftTimer = null;
  }

  componentDidMount() {
    const {path, newStore, params, location} = this.props;
    let _params = (location.search && searchToQuery(location.search)) || params;
    newStore.init(path, _params).then((res) => {
      if (location.pathname.endsWith('/new')) {
        this.setTitle();
      }
      this.autoSaveBegin()
    });
    window.isUmount = false;
    // document.addEventListener('click', this.tryHideReply)
    let viewport = document.querySelector("meta[name=viewport]");
    viewport.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=10,minimum-scale=1,user-scalable=no");

    Api.getEmailSize().then(res => {
      const { remainspace,userid} = res;
      newStore.setState({remainspace: remainspace});
      if(userid != "1" && parseFloat(remainspace)<=parseFloat(0)){
        //管理员不做空间限制
        this.setState({isSpaceFull: true})
      }
    });
    this.textFocus();
  }
  
  componentWillReceiveProps(nextProps) {
    let _params = (this.props.location.search && searchToQuery(this.props.location.search)) || this.props.params;
    if (!shadowEqual(nextProps.params, _params)) {
      this.props.newStore.init(nextProps.path, nextProps.params).then(() => {
        this.setTitle();
      });
    }
    if (!nextProps.location.pathname.endsWith('/new')) {
      this.clearAutoSaveInterval()
    } else if (nextProps.location.pathname.endsWith('/new')) {
      this.clearAutoSaveInterval()
      this.autoSaveBegin()
    }
  }

  shouldComponentUpdate(nextProps) {
    if (this.props.location.pathname.indexOf('/new/end')>-1 && nextProps.history.action === 'POP' && nextProps.path.indexOf('/new')>-1 && !nextProps.newStore.continueWrite) {
      this.props.history.go(-1);
      return false;
    }
    return true
  }
  
  componentWillUnmount() {
    window.isUmount = true;
    TitleUtil.setTitle('');
    this.props.newStore.clearState();
    // document.removeEventListener('click', this.tryHideReply);
    if (this.currentModal && typeof this.currentModal.close === 'function') {
      this.currentModal.close();
    }
    this.clearAutoSaveInterval()
  }
  
  setTitle = () => {
    const {newStore} = this.props;
    const {config: {flag}} = newStore;
    let title = (
      (flag === 1 || flag === 2 || flag === 6 || flag === 7) ? getLabel(126369, '回复'):
      (flag === 3) ? getLabel(385514, '转发') :
      (flag === 4) ? getLabel(129828, '草稿') : 
      getLabel(30912, '写信')
    );
    TitleUtil.setTitle(title);
  }

  // 开始自动保存草稿
  autoSaveBegin = (res) => {
    const { newStore: { autoSave, autofrequency } } = this.props
    let need_autoSave = (res && res.autoSave) || autoSave, need_autofrequency = (res && res.saveInterval * 60 * 1000) || autofrequency
    if (need_autoSave) {
      // need_autofrequency = 3000;
      this.autoSaveDraft(need_autofrequency)
    }
  }

  // 自动保存草稿
  autoSaveDraft = (autofrequency) => {
    const aotuSavaFun = () => {
      this.props.newStore.sendEmail({isDraft: true, autoSave: true})
    }
    this.autoSaveDraftTimer = setInterval(aotuSavaFun, autofrequency);
  }

  clearAutoSaveInterval = () => {
    if (this.autoSaveDraftTimer) {
      clearInterval(this.autoSaveDraftTimer)
    }
    this.autoSaveDraftTimer = null;
  }

  getFields = (form, conditions) => {
    const { elliStatus, filterRerson, classification, setState, curHumanId, config } = this.props.newStore;
    let { conditioninfo, isInit } = form;
    conditioninfo = conditions || toJS(conditioninfo);
    const fields = [];
    if (isInit) {
      conditioninfo.forEach((group) => {
        group.items.forEach((field) => {
          // 处理隐藏判断
          if (typeof(field.hide) === 'boolean' && field.hide) {
            return;
          }
          if (typeof(field.hide) === 'function') {
            if (field.hide(toJS(form.formData), field)) {
              return;
            }
          }
          
          // field中必须的onChange事件，用于调用form的方法
          const onFieldChange = (...args) => {
            if (field.onChange) {
              const onChangeValue = field.onChange(...args);
              if (onChangeValue instanceof Promise) {
                onChangeValue.then(() => {
                  form.onChange.apply(this, args);
                });
              } else {
                form.onChange.apply(this, args);
              }
            }
          };
          
          const domkey = field.domkey.join('__');
          // Form.Item的属性
          let formProps = {
            key: domkey,
            form,
            fieldConfig: field,
            // 分别发送的提醒
            extra: ((domkey === 'internaltonew' || domkey === 'to')&& elliStatus.separate) ?
              <div className="email-new-form-item-tip">{getLabel(504604, '群发时，每个收件人将收到单独发给他/她的邮件')}</div> :
              null,
            onChange: onFieldChange,
            itemProps: field.itemProps,
            children: field.otherCom,
          };
          // 对收件人的特殊处理
          if (field.conditionType === 'MailInput') {
            field.conditionType = 'CUSTOM';
            formProps.itemProps = {...field.itemProps, extra: [
              <Icon type="tianjia" onClick={() => this.chooseOuterInput(domkey)}/>,
              <Icon type='mail-contact-person' onClick={() => this.chooseOuterInnerInput(domkey)}/>
            ], className: `${this.props.prefixCls}-form-mailInput`}
            formProps.fieldConfig = field;
            let value = toJS(form.formData[domkey].value);
            formProps.children =
              <MailInput
                value={value}
                handleOverflow={(x) => {
                  const {newStore} = this.props;
                  newStore.setState({hasOverflow: x});
                }}
                onChange={(e, v) => {
                  onFieldChange(field, v);
                }}
              />;
          }
          if (domkey === 'hrmAccountid') {
            formProps.onChange = (...args) => {
              let hrmId = args[1];
              onFieldChange(...args);
              setState({curHumanId: toJS(args[1])})
              form.updateFields({classification: {value: classification[hrmId]}});
              filterRerson({classification: classification[hrmId]})
            }
          }
          if (domkey === 'classification') {
            let others = [1, 2, 3, 5, 6, 7];
            fields.push(
              <Select
                value={toJS(classification)[curHumanId]}
                label={getLabel('500520','密级')}
                className={'email-new-form-classification'}
                viewAttr={!others.includes(config.flag) ? 3 : 1}
                options={toJS(config.resourceClassification)[curHumanId]}
                onChange={(key, showname) => {
                  this.currentModal = Modal.alert(getLabel('515182','变更密级，发送时，不符合密级要求的收件人将被过滤，请注意收件人是否属于合适密级。'), '', [
                    { text: getLabel('826', '确定'), onPress: () => {
                      new Promise((resolve) => {
                        if (!((form.formParams.classification === '3' && key === '4') || 
                              (form.formParams.classification === '4' && key === '3'))) {
                          resolve('refresh')
                        } else {
                          resolve();
                        }
                      }).then((value) => {
                        if (value === 'refresh') {
                          filterRerson({classification: key})
                        }
                        setState({classification: {...toJS(classification), [curHumanId]: key}})
                        let secrecyfield = {...field, options: toJS(config.resourceClassification)[curHumanId]}
                        onFieldChange(secrecyfield, key);
                      })
                    } },
                  ])
                }}
              />
            )
          } else {
            fields.push(<Form.Item {...formProps}/>);
          }
        });
      });
    }
    return fields;
  }
  
  chooseOuterInput = (domkey) => {
    const {newStore} = this.props, { outerInputBrowserStore } = newStore;
    this.props.history.push(outerInputBrowserStore.path);
    newStore.setState({outerInputDomkey: domkey});
  }

  chooseOuterInnerInput = (domkey) => {
    const {newStore} = this.props, { innerInputBrowserStore } = newStore;
    this.props.history.push(innerInputBrowserStore.path);
    newStore.setState({outerInputDomkey: domkey});
  }
  
  tryHideReply = (e) => {
    const {newStore} = this.props;
    const replyDom = ReactDOM.findDOMNode(newStore.replyRef);
    if (replyDom && !replyDom.contains(e.target)) {
      newStore.hideReply();
    }
  }

  getArrLength = (formData) => {
    let num = 0;
    formData && toJS(formData.value).forEach(item => {
      if (item.type === 'resource') {
        num += 1;
      } else if (item.type === "all") {
        let userids = item.userids.split(',').filter(v => v !== '');
        let userNum = userids.length;
        num += userNum;
      } else if (item.extra) {
        num += item.extra;
      } else if (!item.extra && item.users && Array.isArray(item.users)) {
        num += (item.users).length;
      } 
    });
    return num;
  }

  getLimited = () => {
    const { newStore } = this.props;
    const { innerForm, isInternal, config } = newStore;
    const internal = isInternal();
    if (!internal || !innerForm) return {islimit: false};
    if (config && String(config.sendcount) && String(config.sendcount) === '-1') return {islimit: false};

    else if (innerForm) {
      let sendToLen = this.getArrLength(innerForm.formData.internaltonew); // 收件人
      let sendccLen = this.getArrLength(innerForm.formData.internalccnew); // 抄送
      let sendbccLen = this.getArrLength(innerForm.formData.internalbccnew); // 密送
      let sumNum = sendToLen + sendccLen + sendbccLen;
      if (config && String(config.sendcount)) {
        return {
          islimit: sumNum > config.sendcount, 
          count: config.sendcount, 
          current: sumNum
        }
      }
    }
  }
  
  textFocus = () => {
    const { newStore: { config } } = this.props;
    const texttype = config && config.texttype;
    if (!String(texttype) && Number(texttype) !== 1) {
      setTimeout(this.textFocus, 100)
    } else {
      if (Number(texttype) === 1) {
        if (!this.textContent) {
          setTimeout(this.textFocus, 100)
        } else {
          this.textContent.focus();
        }
      }
    }
  }
  
  render() {
    const {newStore, path, params, location} = this.props, { replyStore, ckStore, innerForm, outerForm, outerInputBrowserStore, innerInputBrowserStore } = newStore,
      { mailTypes, mailTypesSelected, mailTypeIsChanging,mailTypeChangeEnd, content, elliStatus, timingdate, outerInputDomkey, outerInputValueArray, config, setState, innerInputValueArray, autoLoading } = newStore;
    const form = newStore.isInternal() ? innerForm : outerForm;
    const showLimitMsg = this.getLimited();
    const texttype = config && config.texttype;
    const errorSenddate = config && config.errorSenddate;
    const errorHint = config && config.errorHint;
    const paramsQuery = (location.search && searchToQuery(location.search)) || params;
    const isFromWf = paramsQuery && paramsQuery.hasOwnProperty('requestid');
    const leftConfig = [
      { type: 'voice' },
      { type: 'blog-biaoqing' },
      { type: 'blog-tupian', model: 2 },
      { type: 'tianjia' },
    ];
    return (
      <RouteLayout>
        <div className="email-new wm-route-layout" key="new">
          <Modal
            title = {getLabel('131329', '信息确认')}
            visible={this.state.isSpaceFull}
            maskClosable={true}
            transparent={true}
            closable={() => this.setState({isSpaceFull:false})}
            onClose={() => this.setState({isSpaceFull:false})}
            footer={[{ text: 'Ok', onPress: () =>  this.setState({isSpaceFull:false}) }]}
          >
            {getLabel('83075', '个人可用空间已满，请删除部分邮件后再进行发送')}
        </Modal>
          <div className="mobile-ck-rich-text" ref={(x) => this._container = x}>
            <div className="mobile-ck-rich-text-container">
              <div className="mobile-ck-rich-text-editor" onClick={this.tryHideReply}>
                <div className="mobile-ck-rich-text-editor-title">
                  <Flex className="email-new-form-title">
                      <Flex.Item>
                        <DatePicker
                          value={timingdate}
                          minDate={new Date}
                          onChange={date => newStore.setState({ timingdate: date })}
                        >
                          <Icon type="mail-timing-transmission" />
                        </DatePicker>
                      </Flex.Item>
                      <div className="email-new-form-title-center">
                        <SegmentedControl
                          values={toJS(mailTypes).map(item=>item.value)}
                          selectedIndex={mailTypesSelected}
                          onChange={(e) => newStore.changeMailType(e.nativeEvent.selectedSegmentIndex)}
                        />
                      </div>
                      <Flex.Item>
                        <Popover
                          mask
                          key="email-new-elli"
                          align={{offset:[0,0]}}
                          placement="bottomLeft"
                          visible={newStore.elliVisible}
                          overlay={[
                            <Popover.Item disabled={elliStatus.separate} key="cc">{elliStatus.cc ? getLabel(501091, '取消抄送') : getLabel(19809, '添加抄送')}</Popover.Item>,
                            <Popover.Item disabled={elliStatus.separate} key="bcc">{elliStatus.bcc ? getLabel(501092, '取消密送') : getLabel(19810, '添加密送')}</Popover.Item>,
                            <Popover.Item  key="separate">{elliStatus.separate ? getLabel(127186, '取消分别发送') : getLabel(127185, '分别发送')}</Popover.Item>,
                          ]}
                          onVisibleChange={(v) => {
                            //取消抄送，密送的时候，清空对应框
                            elliStatus.cc?"":innerForm.updateField('internalccnew', []);
                            elliStatus.bcc?"":innerForm.updateField('internalbccnew', []);
                            elliStatus.cc?"":outerForm.updateField('cc', []);
                            elliStatus.cc?"":outerForm.updateField('bcc', []);
                            newStore.setState({elliVisible: v})}
                          }
                          onSelect={newStore.selectNewElli}
                        >
                          <Icon type="ellipsis" />
                        </Popover>
                      </Flex.Item>
                    </Flex>
                </div>
                <div className="mobile-ck-rich-text-editor-content">
                  <div className="email-new-form">
                    
                   {errorSenddate  && <NoticeBar mode="link"  icon={<Icon type="cross-circle" size="xxs" />} onClick={() => alert(getLabel(517413, '当前邮件于{errorSenddate} 发送失败。失败原因：{errorHint}').replace('{errorSenddate}',errorSenddate).replace('{errorHint}',errorHint))}>
                        {getLabel(517413, '当前邮件于{errorSenddate} 发送失败。失败原因：{errorHint}').replace('{errorSenddate}',errorSenddate).replace('{errorHint}',errorHint)}
                    </NoticeBar>
                   }
                    {!errorSenddate && timingdate && timingdate !== '' && <div className="email-new-form-date">{getLabel(501563, '邮件将于')}{timingdate}{getLabel(501564, '发出')}</div>}
                    {showLimitMsg && showLimitMsg.islimit && (
                      <div className="email-new-form-date">
                        {getLabel(512439, '最多发给{count}人，当前{current}').replace('{count}', showLimitMsg && showLimitMsg.count || 0).replace('{current}', showLimitMsg && showLimitMsg.current) }
                      </div>
                    )}
                    <Flex>
                      {form && <Form store={form}>
                        <List>
                          {!mailTypeChangeEnd&&<QueueAnim
                            style={{overflowX: 'hidden'}}
                            onEnd={() => {
                              if (mailTypeIsChanging) {
                                newStore.setState({mailTypeChangeEnd: true});
                                window.setTimeout(()=>{
                                  newStore.setState({mailTypeChangeEnd:false, mailTypeIsChanging: false});
                                },0);
                              }
                            }}
                          >
                            {this.getFields(form, mailTypeIsChanging ? [] : null)}
                          </QueueAnim>}
                        </List>
                      </Form>}
                    </Flex>
                  </div>
                  { Number(texttype) !== 1 && <CKRichEditor text={content} store={ckStore} config={{startupFocus: false}}/>}
                  { 
                    Number(texttype) === 1 && (
                      <div className="email-new-textcontent">
                        <TextareaItem 
                          value={content} 
                          autoHeight
                          ref={el => this.textContent = el}
                          onChange={v => setState({content: v})}
                        />
                      </div>
                    )
                  }
                </div>
              </div>
              {
                Number(texttype) === 0 && (
                  <NoMask
                    wrappedComponentRef={ref => newStore.setReplyRef(ref)}
                    store={replyStore}
                    showInput={false}
                    leftConfig={leftConfig}
                    onEmojiChange={newStore.onEmojiChange}
                    onImgChange={newStore.onImgChange}
                    imgUploadConfig={{uploadUrl:"/api/email/add/uploadImgForRichtext"}}
                    onAtChange={newStore.onAtChange}
                    onBrowserChange={newStore.onBrowserChange}
                    onUploadChange={newStore.onUploadChange}
                    onSpeechChange={newStore.onSpeechChange}
                    onPickerChange={newStore.onPickerChange}
                  />
                )
              }
            </div>
          </div>
          <ButtonGroup data={[
            {
              key: 'clear',
              text: getLabel(220, "草稿"),
              onClick: () => {newStore.sendEmail({isDraft: true, history: this.props.history})},
              disabled: showLimitMsg && showLimitMsg.islimit || autoLoading,
              loading: autoLoading
            },
            {
              key: 'submit',
              text: getLabel(2083, "发送"),
              onClick: () => {newStore.sendEmail({history: this.props.history, isFromWf: isFromWf})},
              type: 'primary',
              disabled: showLimitMsg && showLimitMsg.islimit || autoLoading,
              loading: autoLoading
            }]}/>
        </div>
        <Route
          key="end"
          path={`${path}/end`}
          render={() => {
            return (
              <SendEnd 
                path={`${path}/end`} 
                setTitle={this.setTitle}
                emailPageSearch={paramsQuery}
              />
            );
          }}
        />
        <div style={{ display: 'none '}}>
          <Browser
            store={outerInputBrowserStore}
            type="emailOuterInput"
            valueArray={outerInputValueArray}
            isSingle={false}
            onOk={(ids, names, datas) => {
              let newValue = [...form.formData[outerInputDomkey].value, ...datas];
              form.updateField(outerInputDomkey, newValue);
              newStore.setState({outerInputValueArray: [], outerInputBrowserStore: new Browser.Store({route: path})});
            }}
            onCleanUp={() => {
              form.updateField(outerInputDomkey, []);
              newStore.setState({outerInputValueArray: []})
            }}
          />
        </div>
        <div style={{ display: 'none '}}>
          <BrowserHrm
            store={innerInputBrowserStore}
            type={17}
            dataParams={{from: 'email'}}
            valueArray={innerInputValueArray}
            isSingle={false}
            onChange={(ids, names, datas) => {
              if (ids && datas && datas.length > 0) {
                let emailArr = toJS(datas).map(data => {
                  return {
                    id: data.email || data.emailspan || '',
                    name: data.lastnamespan,
                  }
                })
                const filterFun = (arr, param) => {
                  if (!arr || arr.length === 0) return
                  let tempArr = []
                  arr.map(v => {
                    if (!tempArr.some(val => val[param] === v[param])) {
                      tempArr.push(v)
                    }
                  })
                  return tempArr
                }
                let newArr = filterFun(emailArr, 'id')
                let newDatas = newArr.map(v => ({id: v.id, name: `${v.name}< ${v.id} >`}))
                let newValue = [...form.formData[outerInputDomkey].value, ...newDatas];
                form.updateField(outerInputDomkey, newValue);
                newStore.setState({innerInputValueArray: []});
                
                // filterOutEmail({ ids }).then(res => {
                //   if (res.emailAddress && res.emailAddress.length === 0) {
                //     Bubble.error(getLabel('518115','当前所选人员暂无邮箱可用'))
                //   } else {
                //     const filterFun = (arr, param) => {
                //       if (!arr || arr.length === 0) return
                //       let tempArr = []
                //       arr.map(v => {
                //         if (!tempArr.some(val => val[param] === v[param])) {
                //           tempArr.push(v)
                //         }
                //       })
                //       return tempArr
                //     }
                //     let newArr = filterFun(res.emailAddress, 'id')
                //     let newDatas = newArr.map(v => ({id: v.id, name: `${v.name}< ${v.id} >`}))
                //     let newValue = [...form.formData[outerInputDomkey].value, ...newDatas];
                //     form.updateField(outerInputDomkey, newValue);
                //     newStore.setState({innerInputValueArray: []});
                //   }
                // })
              }
            }}
          />
        </div>
      </RouteLayout>
    );
  }
}